import gcoord from 'gcoord'
import type { WeatherData, WeatherInfo } from '@/types/base'
class ApiAdapter {
  apiType: string = 'gaode'
  apiKey: string = ''
  secret: string = ''
  latitude: number = 0
  longtitude: number = 0
  constructor(latitude: number, longtitude: number) {
    console.log(import.meta.env)
    this.apiType = import.meta.env.VITE_APP_API_TYPE
    this.latitude = latitude
    this.longtitude = longtitude
    //   获取apiKey配置信息
    const apiKey = import.meta.env.VITE_APP_API_KEY
    if (!apiKey) {
      throw new Error('API_KEY is not defined')
    } else {
      this.apiKey = apiKey
    }
  }
  init():Promise<WeatherData> {
    if (this.apiType && this.apiKey) {
      return this.getApiWeather()
    }
    throw new Error('API_TYPE or API_KEY is not defined');
  }
  getApiWeather() {
    switch (this.apiType) {
      case 'gaode':
        try {
          return this.getWeatherByGaode()
        }catch (e) {
          console.error(e)
          return Promise.resolve({})
        }
      case 'xinzhi':
        try {
          return this.getWeatherByXinzhi()
        }catch (e) {
          console.error(e)
          return Promise.resolve({})
        }

      case 'hefeng':
        try {
          return this.getWeatherByHefeng()
        }catch (e) {
          console.error(e)
          return Promise.resolve({})
        }

      case 'openWeather':
        try {
          return this.getWeatherByOpenWeather()
        }catch (e) {
          console.error(e)
          return Promise.resolve({})
        }
      default:
        return Promise.resolve({})
    }
  }

  async getWeatherByGaode():Promise<WeatherData> {
    // 转换经纬度坐标
    const transedPosition = gcoord.transform([this.longtitude,this.latitude],gcoord.WGS84,gcoord.AMap)
    const ipApiUrl = 'https://restapi.amap.com/v3/assistant/coordinate/convert'
    const convertSendParam = `key=${this.apiKey}&locations=${transedPosition[0]},${transedPosition[1]}&coordsys=gps&output=JSON`
    const locationConverted = await fetch(`${ipApiUrl}?${convertSendParam}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    })
    const resConvert = await locationConverted.json()
    if (resConvert?.status === '1') {
      console.log(resConvert)
      const locationInfo: { infocode: string; locations: string } = resConvert
      // 逆坐标转换，将经纬度转换为城市信息
      const localtionParams = {
        location: `${transedPosition[0]},${transedPosition[1]}`,
        key: this.apiKey,
        output: 'JSON'
      }
      const locationRes = await (await fetch(`https://restapi.amap.com/v3/geocode/regeo?${new URLSearchParams(localtionParams)}`,{
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })).json()
      console.log(locationRes,'地址信息')
      const addressInfo = locationRes.regeocode.addressComponent;
      console.log(addressInfo)
      const {adcode} = addressInfo;
      const url = 'https://restapi.amap.com/v3/weather/weatherInfo'
      const params = {
        key: this.apiKey,
        city: adcode,
        extensions: 'all',
        output: 'JSON',
      }
      const weatherInfo =await(await fetch(`${url}?${new URLSearchParams(params)}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })).json() || {}
      const cityWeatherInfo = (weatherInfo.forecasts || [])[0];
      const {city,province,reporttime,casts} = cityWeatherInfo || {};
      const nowDayReport:any = casts[0];
      return {
        city:{
          city,
          province,
          reporttime
        },
        now:this.transDataByType(this.apiType,nowDayReport),
        dayReport:[]
      }
    } else {
      return Promise.resolve({})
    }
  }
  transDataByType(type:string,inData:any):WeatherInfo{
    switch (type) {
      case 'gaode':
        return {
          city: inData.city,
          temp:inData.daytemp,
          nightTemp:inData.nighttemp,
          weather:inData.dayweather,
          nightWeather: inData.nightweather,
          wind:inData.daywind,
          humidity:inData.dayhumidity
        }
      case 'xinzhi':
        return { nightTemp: 0, nightWeather: '', temp: 0, weather: '' }
      case 'hefeng':
        return { nightTemp: 0, nightWeather: '', temp: 0, weather: '' }
      case 'openWeather':
        return { nightTemp: 0, nightWeather: '', temp: 0, weather: '' }
      default:
        return { nightTemp: 0, nightWeather: '', temp: 0, weather: '' }
    }
  }
  getWeatherByXinzhi() {
    return Promise.resolve({})
  }
  getWeatherByHefeng() {
    return Promise.resolve({})
  }
  getWeatherByOpenWeather() {
    return Promise.resolve({})
  }
}

export { ApiAdapter }
